<?php

namespace controller;

/**
 * lista produktów z danej kategorii w sklepi
 *
 * @author Damian
 */
class Shop_Category extends Shop {

    public function __construct($options = array()) {
        try{
            parent::__construct($options);
        }  catch (exceptions\CategoryNotFoundException $e){
           $session = \library\Registry::get("session");
           $session->set("error",$e->getMessage());
        }
    }

    public function index() {
        $session = \library\Registry::get("session");
        $view = $this->getActionView();
        $layoutView = $this->getLayoutView();
        if($session->get("error")){
            $view->set("error",$session->get("error"));
            $layoutView->set("paneltitle", $session->get("error"));
            $this->render();
            return;
        }
       // var_dump($_GET);
        $featuresFilter = ($session->get("featuresFilters"))?$session->get("featuresFilters"): array();
        if (\library\RequestMethods::get("feature",null,false)){
            $filtr = \library\RequestMethods::get("feature",null,false);
            $featuresFilter[key($filtr)]=$filtr[key($filtr)];
            if (isset($filtr["clear"])){
                $featuresFilter=array();
                $session->erase("featuresFilters");
            }
        }
        else if (!\library\RequestMethods::get ("page") && !\library\RequestMethods::get ("order")){
            $featuresFilter=array();
            $session->erase("featuresFilters");
        }
        $session->set("featuresFilters",$featuresFilter);
       
        $IDs = $this->category->getAllIds();
        
        $page = (\library\RequestMethods::get("Page")) ? \library\RequestMethods::get("Page") : 1;
        if (!is_numeric($page)) {
            $page = 1;
        }

         $layoutView->set("featuresFilters",$featuresFilter);
        if (sizeof($featuresFilter)>0){
            $layoutView->set("clearFilters",true);
        }
        $allCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID)
                ->where(\model\TblProduct::ACTIVE, "=", 1,  \model\TblProduct::getModel()->getTable(), " and ")                
                ->in(\model\TblProduct::CATEGORY_ID, $IDs,  \model\TblCategory::getModel()->getTable()," and ");                
        $productsCriteria=  \model\TblProduct::getModel()->createCriteria($this->shop->ShopID)
                ->where(\model\TblProduct::ACTIVE, "=", 1,  \model\TblProduct::getModel()->getTable(), " and ")                
                ->in(\model\TblProduct::CATEGORY_ID, $IDs,  \model\TblCategory::getModel()->getTable()," and ")
                ->limit($this->perPage, $page);
        if (sizeof($featuresFilter)==1){
                $allCriteria->join(\model\TblProductFeature::getModel())
                            ->where(\model\TblProductFeature::VALUE,"=",$featuresFilter[key($featuresFilter)],  \model\TblProductFeature::getModel()," and ");
                $productsCriteria->join(\model\TblProductFeature::getModel())
                            ->where(\model\TblProductFeature::VALUE,"=",$featuresFilter[key($featuresFilter)],  \model\TblProductFeature::getModel()," and ");
        }
        if (sizeof($featuresFilter)>1){
            $valueIDs=array();
            foreach ($featuresFilter as $featureFilter){
                $valueIDs[]=$featureFilter;
            }
            $allCriteria->join(\model\TblProductFeature::getModel())
                            ->in(\model\TblProductFeature::VALUE,$valueIDs,  \model\TblProductFeature::getModel()," and ");
                $productsCriteria->join(\model\TblProductFeature::getModel())
                             ->in(\model\TblProductFeature::VALUE,$valueIDs,  \model\TblProductFeature::getModel()," and ");
        }
                $all= $allCriteria->count();
        $layoutView->set("paneltitle","Produkty z kategorii ".$this->category->Name);
        $list = $this->category->createBreadCramps();
        $view->set("CategoryList", $list);       
       
        if (\library\RequestMethods::get("from") && is_numeric(\library\RequestMethods::get("from"))){
            $productsCriteria->where(\model\TblProduct::GROSS_PRICE, ">=", \library\RequestMethods::get("from"),  \model\TblProduct::getModel()->getTable()," and ");
            $layoutView->set("from",\library\RequestMethods::get("from"));
        }
         if (\library\RequestMethods::get("to") && is_numeric(\library\RequestMethods::get("to"))){
            $productsCriteria->where(\model\TblProduct::GROSS_PRICE, "<=", \library\RequestMethods::get("to"),  \model\TblProduct::getModel()->getTable()," and ");
            $layoutView->set("to",\library\RequestMethods::get("to"));
        }
        if (\library\RequestMethods::get("order")){
            $session->set("order",\library\RequestMethods::get("order"));
            }
        $view->set("order",$session->get("order"));
        $order = \model\TblProduct::createOrderString($session->get("order"));
        $productsCriteria->order($order[0], $order[1],  \model\TblProduct::getModel()->getTable());
        $Products = \model\TblProduct::getModel()->all($productsCriteria);
        $pagesCount = ceil($all / $this->perPage);
        $pages = new \view\Pagination($page, 1, $pagesCount, "./" . $this->shop->URL . "/" . "sm");
        if ($Products) {
            $view->set("productsPictures", $Products);
            $layoutView->set("pages",$pages);
        }
        $database = \library\Registry::get("database");
        /* @var $database \model\database\PDOConnector */
            $maxMinCriteria = new \model\Criteria();
        $maxMinCriteria->from(\model\TblProduct::getModel()->getTable(),
    ["max(`".\model\TblProduct::GROSS_PRICE."`)"=>"`max`",
        "min(`".\model\TblProduct::GROSS_PRICE."`)"=>"`min`"])
                ->where(\model\TblProduct::VISABLE, "=", 1,false," ")
                ->where(\model\TblProduct::ACTIVE, "=", 1,false," and ")
                 ->join(\model\TblCategory::getModel())
                ->join(\model\TblProductPicture::getModel())
                 ->in(\model\TblProduct::CATEGORY_ID, $IDs,  \model\TblCategory::getModel()->getTable()," and ")
                ->where(\model\TblProductPicture::DEFAULT_PICTURE, "=", 1,  \model\TblProductPicture::getModel()->getTable()," and ");        
       $minMax = $database->executeSQL($maxMinCriteria->getSelectQuery())->fetch(\PDO::FETCH_ASSOC);
       $min = floatval($minMax["min"]);
       $max = floatval($minMax["max"]);
       if ($min==$max){
           $max*=1.1;
           $min=  round($min/1.1,1);
       }
        if (\library\RequestMethods::get("from") && is_numeric(\library\RequestMethods::get("from"))){
            $layoutView->set("from",\library\RequestMethods::get("from"));
        }
        else {
            $layoutView->set("from",$min);
        }
         if (\library\RequestMethods::get("to") && is_numeric(\library\RequestMethods::get("to"))){
            $layoutView->set("to",\library\RequestMethods::get("to"));
        }
        else {
            $layoutView->set("to",$max);
        }
       $step = ($max-$min)/100.0;
       $layoutView->set("min",$min);
       $layoutView->set("max",$max);
       $layoutView->set("step",$step);
       $session->set("category",  $this->category);
        $view->set("category", $this->category);
        $view->set("category", $this->category);
        $categoryFeaturesCriteria = new \model\Criteria();
        $categoryFeaturesCriteria->from(\model\TblCategoryFeature::getModel()->getTable())
                ->where(\model\TblCategoryFeature::CATEGORY_ID, "=", $this->category->CategoryID)
                ->order(\model\TblCategoryFeature::NAME);
        $categoryFeatures = new \model\DataTable(\model\TblCategoryFeature::getModel()->all($categoryFeaturesCriteria));
        $categoryFeaturesData = $categoryFeatures->getModelData(true);
        foreach ($categoryFeaturesData as &$feature){
            $valuesCriteria = new \model\Criteria();
            $valuesCriteria->from(\model\TblFeatureValue::getModel()->getTable())
                    ->where(\model\TblFeatureValue::CATEGORY_FEATURE_ID, "=", $feature->CategoryFeatureID);
            $values = new \model\DataTable(\model\TblFeatureValue::getModel()->all($valuesCriteria),false);
            $valuesData = $values->getModelData(true);
            foreach ($valuesData as &$value){
                    $value->URL="?feature[".$feature->CategoryFeatureID."]=".$value->FeatureValueID;  
                    $countCriteria = new \model\Criteria();
                    $value->count = $countCriteria->from(\model\TblProductFeature::getModel()->getTable())
                            ->where(\model\TblProductFeature::VALUE,"=",$value->FeatureValueID)->count();
                    
            }
            $feature->Values=$valuesData;
        }
        if (sizeof($categoryFeaturesData)>0){
            $layoutView->set("categoryFeaturesData",$categoryFeaturesData);
        }
        $this->render();
    }

}
